<?php
define("SECKEY", "uyrd{STR}63o");
define("AESKEY", "0060413069bbcb11993f1aa16c876cf0");

// MySQL 连接池
include("libs/MySQL.php");
// 少女前线辅助核心代码
include("libs/GirlsFrontline.php");
// Redis 数据库和连接池代码
include("libs/RedisDB.php");
include("libs/RedisPool.php");

$server = new swoole_http_server('0.0.0.0', 80);
$server->set(['work_num' => 1]);

// MySQL 配置
$server->mysqlConfig = [
	"host"     => "数据库地址",
	"port"     => 3306,
	"user"     => "数据库账号",
	"password" => "数据库密码",
	"database" => "数据库名称",
	"timeout"  => 5
];

// Redis 配置
$server->redisConfig = [
	// 主库
	"master" => [
		"host"             => "localhost", // 服务器地址
		"port"             => 6379,        // 服务器端口
		"pool_size"        => 100,         // 连接池大小
		"pool_get_timeout" => 1000         // 连接超时时间
	],
	// 从库（没有的话就和主库一样）
	"slave" => [
		"host" => "localhost", // 服务器地址
		"port" => 6379         // 服务器端口
	],
];

$server->on('WorkerStart', function ($request, $response) use ($server) {
	
	// 初始化 MySQL 连接池
    MysqlPool::getInstance()->init($server->mysqlConfig)->recycleFreeConnection();
	
	// 初始化 Redis 连接池
	RedisPool::getInstance($server->redisConfig);
});

$server->on('Request', function ($request, $response) use ($server) {
	// 参数传统化
	$_GET = $request->get;
	if(GirlsFrontline::ValidArgs($_GET)) {
		
		$response->header("Content-Type", "application/json");
		$decKey   = $_GET['a'];
		$fullKey  = str_replace("{STR}", $_GET['a'], SECKEY);
		$decoded  = GirlsFrontline::DataSwitch(GirlsFrontline::Hex2String($_GET['aaa']), $fullKey);
		$userData = json_decode($decoded, true);
		
		if(is_array($userData)) {
			if(!isset($userData['id']) || !GirlsFrontline::ValidKey($userData['id'], AESKEY)) {
				$response->end(GirlsFrontline::GetFormatMsg("激活码不正确!", 301, $fullKey));
			} elseif(!isset($userData['openId']) || !preg_match("/^[0-9]+$/", $userData['openId'])) {
				$response->end(GirlsFrontline::GetFormatMsg("请用激活码绑定的账号登陆,一个激活绑定一个账号,不能换绑!", 301, $fullKey));
			} else {
				
				// 查询 Redis 缓存
				$redis = RedisPool::getInstance($server->redisConfig)->get();
				$rsUse = $redis->get("gfKey-{$userData['id']}");
				if($rsUse) {
					$response->end($rsUse);
				} else {
					
					// 查询数据库
					$conn = MysqlPool::getInstance()->getConn();
					$key  = $conn->escape($userData['id']);
					$rs   = $conn->query("SELECT * FROM `gf`.`key` WHERE `id`='{$key}'");
					MysqlPool::getInstance()->recycle($conn);
					$result = "";
					
					if(is_array($rs) && count($rs) == 1) {
						if($rs[0]['expiretime'] < time()) {
							$result = GirlsFrontline::GetFormatMsg("激活失败!您的激活码到期日期为:" . date("Y-m-d", $rs[0]['expiretime']) . ",已经过期,请及时续费!", 301, $fullKey);
						} elseif($rs[0]['openid'] !== $userData['openId']) {
							$result = GirlsFrontline::GetFormatMsg("请用激活码绑定的账号登陆,一个激活绑定一个账号,不能换绑!", 301, $fullKey);
						} elseif($rs[0]['status'] == "banned") {
							$result = GirlsFrontline::GetFormatMsg("此激活码已被禁用", 301, $fullKey);
						} else {
							$lastuse  = time();
							$totaluse = Intval($rs[0]['totaluse']) + 1;
							// 更新激活码使用统计
							$conn->query("UPDATE `gf`.`key` SET `lastuse`='{$lastuse}', `totaluse`='{$totaluse}' WHERE `id`='{$key}'");
							$result = GirlsFrontline::GetFormatMsg("登录成功!", 0, $fullKey);
						}
						
						// 缓存数据到 Redis
						$redis->set("gfKey-{$userData['id']}", $result);
						$redis->expireAt("gfKey-{$userData['id']}", time() + 300);
						
						// 输出结果
						$response->end($result);
					} else {
						$response->end(GirlsFrontline::GetFormatMsg("激活码不存在!", 301, $fullKey));
					}
				}
			}
		} else {
			$response->status(403);
			$response->end("403 Forbidden");
		}
	} else {
		$response->status(403);
		$response->end("403 Forbidden");
	}
});

$server->start();
